package com.mgs.product.tagger.handlers
{
	import com.mgs.fwk.context.ApplicationContext;
	import com.mgs.fwk.handlers.ActionHandler;
	import com.mgs.product.tagger.controller.ContextController;
	import com.mgs.product.tagger.actions.ApplicationAction;
	import com.mgs.product.tagger.actions.DeleteDocumentAction;
	import com.mgs.product.tagger.dao.DocumentDao;
	import com.mgs.product.tagger.dao.DocumentDaoImpl;
	import com.mgs.product.tagger.model.Classifiable;
	import com.mgs.product.tagger.model.Segment;
	import com.mgs.product.tagger.ui.dto.ClassifiableUI;
	import com.mgs.product.tagger.ui.dto.DocumentUI;
	import com.mgs.product.tagger.ui.dto.NavigationContext;
	
	public class DeleteDocumentHandler implements ActionHandler
	{
		public var documentDao:DocumentDao = new DocumentDaoImpl();
		
		public function DeleteDocumentHandler()
		{
		}
		
		public function execute(context:ApplicationContext, action:ApplicationAction):void
		{
			var document:DocumentUI = (action as DeleteDocumentAction).document;
			// delete file
			documentDao.deleteDocument((context as NavigationContext).repository, document.document);
			// remove from elements (if no tags or in all tags)
			if(document.document.tags.length == 0)
			{
				(context as NavigationContext).classification.elements.splice((context as NavigationContext).classification.elements.indexOf(document.document), 1);
			}
			else
			{
				for each(var segment:Segment in document.document.tags)
				{
					segment.taggedElements.splice(segment.taggedElements.indexOf(document.document), 1);
				}
			}
			for each(var elementUI:ClassifiableUI in (context as NavigationContext).elements.toArray())
			{
				if(elementUI is DocumentUI && (elementUI as DocumentUI).document == document.document)
				{
					(context as NavigationContext).elements.removeItemAt((context as NavigationContext).elements.getItemIndex(elementUI));
					break;
				}
			}
			
			ContextController.updateContextDescription(context as NavigationContext);
		}
	}
}